﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace up6.db.utils
{
    public class PathTool
    {

        /// <summary>
        /// 自动创建多层级路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="separator">路径分隔符，默认：/</param>
        public static void createDirectory(string path, char separator = '/')
        {
            var dirs = path.Split(separator);
            var folder = "";
            foreach (var dir in dirs)
            {
                if (folder != "")
                {
                    folder = folder + "/" + dir;
                }
                else
                {
                    folder = dir;
                }
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                System.Diagnostics.Debug.WriteLine(folder);
            }
        }

        public static string getExtention(String n)
        {
            String name = getName(n);

            int extIndex = name.LastIndexOf(".");
            //有扩展名
            if (-1 != extIndex)
            {
                String ext = name.Substring(extIndex + 1);
                return ext;
            }
            return "";
        }

        public static void mkdirsFromFile(String f)
        {
            String dir = parentDir(f);
            PathTool.createDirectory(dir);
        }

        public static bool mkdir(string dir)
        {
            if(!Directory.Exists(dir))
            {
                var inf = Directory.CreateDirectory(dir);
                return inf.Exists;
            }
            return true;
        }

        /// <summary>
        /// 合并路径，自动判断结尾符
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string combin(string a,string b)
        {
            if(a.EndsWith("/") || a.EndsWith("\\")) a=a.Remove(a.Length-1, 1);
            if (b.StartsWith("/")||b.StartsWith("\\")) b=b.Remove(0, 1);

            return a + "/" + b;
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        /// <param name="byteCount"></param>
        /// <returns></returns>
        public static string BytesToString(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
            if (byteCount == 0)
                return "0" + suf[0];
            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return (Math.Sign(byteCount) * num).ToString() + suf[place];
        }

        /// <summary>
        /// 获取路径中的文件名称（或目录名称）
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static string getName(string n)
        {
            n = n.Replace('\\', '/');
            var pos = n.LastIndexOf('/');
            if (pos == -1) return n;
            return n.Substring(pos + 1);
        }

        /// <summary>
        /// 取父级目录并自动转换分隔符
        /// C:\soft\qq.exe => C:/soft
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static string parentDir(string n)
        {
            return Path.GetDirectoryName(n).Replace('\\', '/');
        }

        /// <summary>
        /// 从文件路径中创建目录
        /// </summary>
        /// <param name="filePath"></param>
        public static void mkdirFromFile(string filePath)
        {
            var dir = parentDir(filePath);
            createDirectory(dir);
        }

        public static string url_safe_encode(string v)
        {
            StringBuilder sb = new StringBuilder();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(v); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < bytes.Length; i++)
            {
                if(isReverseChar((char)bytes[i]))
                {
                    sb.Append((char)bytes[i]);
                }
                else
                {
                    sb.Append("%");
                    sb.Append(byteToHex(bytes[i]));
                }
            }

            v = sb.ToString();
            v = v.Replace("+", "%20");
            v = v.Replace("*", "%2A");
            return v;
        }

        public static string url_decode(string v)
        {
            return HttpUtility.UrlDecode(v);
        }

        /// <summary>
        /// 保留字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool isReverseChar(char c)
        {
            return 
                ((c >= 'a' && c <= 'z') || 
                (c >= 'A' && c <= 'Z') || 
                (c >= '0' && c <= '9')|| 
                c == '-' || 
                c == '_' || 
                c == '.' ||
                c == '/' || 
                c == ':' || 
                c == '?' || 
                c == '~');
        }

        public static string byteToHex(byte b)
        {
            return b.ToString("X2");
        }
    }
}